import { createVNode, render } from 'vue'
import { Router } from 'vue-router'
import { ElMessage } from 'element-plus'
import loadingBar from '@/components/loadingBar.vue'
import { useMenuStore } from '@/store/menu'
import resetStore from '@/store/resetStore'

function loopMenuList(menuList: any, path: string): any {
    for (let i in menuList) {
        if (menuList[i].path == path) {
            return true
        }
        if (menuList[i].children && menuList[i].children.length > 0) {
            let res = loopMenuList(menuList[i].children, path)
            if (res) {
                return true
            }
        }
    }
}

// 路由守卫
export function routerGuards(router: Router) {
    const menuStore = useMenuStore()
    // 组件加载动画loading
    const VNode = createVNode(loadingBar)
    // 验证权限处理：全局守卫路由
    const whiteList = ['/login']    // 路由白名单
    router.beforeEach(async (to, from, next) => {
        render(VNode, document.body)
        if (to.path === '/404') {
            next()
        } else {
            const token = localStorage.getItem('token')
            if (token) {
                if (to.path === '/login') {
                    ElMessage.success('你已经登录！')
                    next({ path: '/' })
                } else {
                    if (!menuStore.getIsGetMenuList) {
                        try {
                            await menuStore.getMenuListAndAuth()
                            next({ ...to, replace: true })
                        } catch (error) {
                            localStorage.clear()
                            sessionStorage.clear()
                            next({ path: '/login' })
                        }
                    } else {
                        let hasRoles = menuStore.getMenuList
                        const auth = loopMenuList(hasRoles, to.path)
                        if (auth) {
                            next()
                        } else {
                            next({ path: '/404' })
                        }
                    }
                }
            } else {
                // 判断是否在白名单中
                if (whiteList.indexOf(to.path) !== -1) {
                    // 在白名单中继续访问
                    next()
                } else {
                    // 不在白名单中跳登录页面
                    ElMessage.warning('请先登录！')
                    sessionStorage.clear()
                    localStorage.clear()
                    resetStore()
                    next({ path: '/login' })
                }
            }
        }
    })

    router.afterEach((to, from) => {
        VNode.component?.exposed?.loading.close()
        document.title = to.meta.title ? `ZeusAdmin - ${to.meta.title}` : 'ZeusAdmin'
    })
}